import httpx  # pip install httpx
from httpx_sse import connect_sse, aconnect_sse  # pip install httpx-sse
import asyncio

def sse_with_httpx1(url, headers):
    # 使用 httpx.stream 发送 GET 请求并流式处理响应
    # with httpx.stream("GET", url) as response:
    with httpx.stream("POST", url) as response:
        for data in response.iter_bytes():  # 迭代响应的字节数据
            print(data)  # 处理每一块数据


# 异步处理 SSE
async def sse_with_httpx2(url, headers):
    async with httpx.AsyncClient() as client:
        # async with client.stream('GET', url) as response:
        async with client.stream('POST', url) as response:
            async for line in response.aiter_lines():
                print(line)


def sse_with_httpxsse1(url, headers):
    with httpx.Client() as client:
        # with connect_sse(client, "GET", url) as event_source:
        with connect_sse(client, "POST", url) as event_source:
            for sse in event_source.iter_sse():
                print(sse.event, sse.data, sse.id, sse.retry)

# 异步处理SSE
async def sse_with_httpxsse2(url, headers):
    async with httpx.AsyncClient() as client:
        # async with aconnect_sse(client, "GET", url) as event_source:
        async with aconnect_sse(client, "POST", url) as event_source:
            async for event in event_source.aiter_sse():
                print(f"Received async update: {event.data}")


if __name__ == "__main__":
    url = "http://127.0.0.1:8080/sse2"
    headers = {"Accept": "text/event-stream"}
    
    # 运行
    # sse_with_httpx1(url, headers)
    # sse_with_httpxsse1(url, headers)
    
    # 运行异步任务
    asyncio.run(sse_with_httpx2(url, headers))
    # asyncio.run(sse_with_httpxsse2(url, headers))